package com.love_weinuo.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.TileOverlay;
import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.UrlTileProvider;
import com.lzy.okgo.callback.StringCallback;
import com.tencent.qcloud.uikit.common.utils.ImageUtil;
import com.love_weinuo.R;
import com.love_weinuo.bean.AddCodeCallBackBean;
import com.love_weinuo.bean.Location;
import com.love_weinuo.bean.ZxingCallBackBean;
import com.love_weinuo.databinding.ActivityPindanZxingDescBinding;
import com.love_weinuo.ui.BaseActivity;
import com.love_weinuo.util.BHThreadPool;
import com.love_weinuo.util.GsonUtil;
import com.love_weinuo.util.HTTPAPI;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.PermissionUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.ToastUtil;
import com.love_weinuo.util.maputil.MapImageCache;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.tencent.qcloud.uikit.common.utils.ImageUtil.saveFile;
import static com.love_weinuo.bean.Constants.LOGINPRESSION;
import static com.love_weinuo.bean.Constants.REQEEST_CDOE_GPS;

/**
 * Created by Administrator on 2019/3/24.
 */

public class PindanZxingDescActivity extends BaseActivity {

    ActivityPindanZxingDescBinding binding;
    ZxingCallBackBean.ResultEntity.ResEntity bean;
    String result;
    ZxingCallBackBean.ResultEntity resultEntity;
    Location location = new Location();
    AMapLocationClient mLocationClient = null;
    AMapLocationClientOption mLocationOption = null;
    MyAMapLocationListener listener = new MyAMapLocationListener();
    MapView mMapView = null;
    AMap aMap;
    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/amapdemo/Cache/";
    private TileOverlay mtileOverlay;
    List<LatLng> lists = new ArrayList();
    String inviteCode = (String) SpUtils.get("module_broadcast_groupid", "");

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pindan_zxing_desc);
        binding.setActivity(this);
        mMapView = findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);
        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        add(this);
        setBack();
        setTitleText("拼单详情");
        if (TextUtils.isEmpty(inviteCode)) {
            binding.etModuleInviteCode.setText(inviteCode);
        }
        binding.tvModuleBT.setOnClickListener(this);
        result = getIntent().getStringExtra("module_result");
        ZxingCallBackBean zxingCallBackBean = GsonUtil.GsonToBean(result, ZxingCallBackBean.class);
        resultEntity = zxingCallBackBean.getResult();
        bean = resultEntity.getRes();
        binding.tvModuleSeeAllOrder.setVisibility(View.GONE);
        binding.setBean(bean);
        binding.tvModuleArea.setText(bean.getHasland() + "");
        binding.tvModuleAllSize.setText(bean.getSumarea() + "");
        binding.tvModuleStartTime.setText(bean.getStarttime().split(" ")[0]);
        binding.tvModuleEndTime.setText(bean.getEndtime().split(" ")[0]);

        if (0 == resultEntity.getIsleader()) {
            LogUtil.e("是发布者");
            addCode();
            binding.llModuleInvite.setVisibility(View.VISIBLE);
            binding.ilModuleView.setVisibility(View.VISIBLE);
            binding.llModuleInputInvite.setVisibility(View.GONE);
            binding.tvModuleBT.setText("进入聊天");
        } else {
            if (1 == resultEntity.getIsleader()) {
                LogUtil.e("不是发布者，未加入拼单");
                binding.llModuleInvite.setVisibility(View.GONE);
                binding.ilModuleView.setVisibility(View.GONE);
                binding.llModuleInputInvite.setVisibility(View.VISIBLE);
                binding.tvModuleBT.setText("加入拼单");
            } else if (0 == resultEntity.getIsjoin()) {
                LogUtil.e("不是发布者，已加入拼单");
                addCode();
                binding.llModuleInvite.setVisibility(View.VISIBLE);
                binding.ilModuleView.setVisibility(View.VISIBLE);
                binding.llModuleInputInvite.setVisibility(View.GONE);
                binding.tvModuleBT.setText("进入聊天");
            }
        }
        /**
         * 通过加入群组来判断是否是群员
         */
        if (TextUtils.isEmpty(resultEntity.getGroupid())) {
            ToastUtil.showToast("数据有误");
            finish();
        }
        initPermission();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rightImage:
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, "我在这里使用直升机喷洒农药");
                intent.putExtra(Intent.EXTRA_SUBJECT, "振航航空");
                intent.putExtra(Intent.EXTRA_TITLE, "好消息");
                Intent chooserIntent = Intent.createChooser(intent, "分享到：");
                startActivity(chooserIntent);
                break;
            case R.id.tvModuleBT:
                toNext();
                break;
            default:
        }
    }

    public void toNext() {
        String str = binding.tvModuleBT.getText().toString().trim();
        LogUtil.e("群组ID==>" + resultEntity.getGroupid());
        switch (str) {
            case "进入聊天":
                ChatActivity.startGroupChat(PindanZxingDescActivity.this, resultEntity.getGroupid());
                finish();
                break;
            case "加入拼单":
                Intent joinIntent = new Intent(PindanZxingDescActivity.this, JoinPindanActivity.class);
                joinIntent.putExtra("module_land_title", bean.getPname());
                joinIntent.putExtra("module_land_size", bean.getSumarea());
                joinIntent.putExtra("module_land_start_time", bean.getStarttime());
                joinIntent.putExtra("module_land_stop_time", bean.getEndtime());
                joinIntent.putExtra("module_porder_num", bean.getPordernum());
                joinIntent.putExtra("module_porder_id", bean.getId());
                joinIntent.putExtra("module_group_id", resultEntity.getGroupid());
                joinIntent.putExtra("module_invite_code", inviteCode);
                startActivity(joinIntent);
                break;
            default:
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOGINPRESSION:
                initGPS();
                break;
            case REQEEST_CDOE_GPS:
                initLocation();
                break;
            default:
        }
    }

    public void initGPS() {
        if (!PermissionUtil.isOPen(this)) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, REQEEST_CDOE_GPS);
        } else {
            initLocation();
        }
    }

    private void initPermission() {
        if (PermissionUtil.loginPermission(this, LOGINPRESSION)) {
            if (!PermissionUtil.isOPen(PindanZxingDescActivity.this)) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, REQEEST_CDOE_GPS);
            } else {
                initLocation();
            }
        }
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(this);
        mLocationClient.setLocationListener(listener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setOnceLocation(true);
        mLocationOption.setOnceLocationLatest(true);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setMockEnable(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.startLocation();
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        //        myLocationStyle.myLocationType((MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE));//连续定位
        //        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.strokeColor(getResources().getColor(R.color.A1E0F2));
        myLocationStyle.strokeWidth(1);
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.HALFA1E0F2));
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        //        aMap.setMyLocationEnabled(true);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                binding.nslModule.requestDisallowInterceptTouchEvent(false);
            }
        });
        useOMCMap();
    }

    /**
     * 加载在线瓦片数据
     */
    private void useOMCMap() {
        final String url = "http://www.google.cn/maps/vt?lyrs=y&gl=cn&x=%d&s=&y=%d&z=%d";
        TileOverlayOptions tileOverlayOptions = new TileOverlayOptions().tileProvider(new UrlTileProvider(256, 256) {
            @Override
            public URL getTileUrl(int x, int y, int zoom) {
                try {
                    String mFileDirName;
                    String mFileName;
                    mFileDirName = String.format("L%02d/", zoom + 1);
                    mFileName = String.format("%s", TileXYToQuadKey(x, y, zoom));
                    String LJ = ALBUM_PATH + mFileDirName + mFileName;
                    if (MapImageCache.getInstance().isBitmapExit(mFileDirName + mFileName)) {
                        return new URL("file://" + LJ);
                    } else {
                        String filePath = String.format(url, x, y, zoom);
                        Bitmap mBitmap;
                        mBitmap = ImageUtil.getImageBitmap(ImageUtil.getImageStream(filePath));
                        try {
                            saveFile(mBitmap, mFileName, mFileDirName);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return new URL(filePath);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        tileOverlayOptions.diskCacheEnabled(false).diskCacheDir("/storage/emulated/0/amap/OMCcache").diskCacheSize(1024000).memoryCacheEnabled(true).memCacheSize(102400).zIndex(-9999);
        if (mtileOverlay == null) {
            mtileOverlay = aMap.addTileOverlay(tileOverlayOptions);
        } else {
            LogUtil.e("mtileOverlay为空");
        }
        //设置地图显示中心店
        LatLng marker1 = new LatLng(getDoublePoint(resultEntity.getPoint().get(0).split(";")[0].split(",")[0]), getDoublePoint(resultEntity.getPoint().get(0).split(";")[0].split(",")[1]));
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));
        showPoints(resultEntity.getPoint());
    }

    public void showPoints(List<String> pointLongs) {
        LogUtil.e("1--》" + resultEntity.getPoint());
        try {
            if (pointLongs.size() != 0) {
                lists.clear();
                for (String latlng : pointLongs) {
                    for (String str : latlng.split(";")) {
                        double lat = getDoublePoint(str.split(",")[0]);
                        double lng = getDoublePoint(str.split(",")[1]);
                        lists.add(new LatLng(lat, lng));
                        LogUtil.e("添加的点" + lat + "  " + lng);
                    }
                }
                if (lists.size() != 0) {
                    lists.add(lists.get(0));
                    LogUtil.e("获取点的个数： " + lists.size());
                    DrawRectangular(lists);
                }
            }
        } catch (Exception e) {
            LogUtil.e("获取土地经纬度点解析失败");
        }
    }

    public double getDoublePoint(String s) {
        BigDecimal bd = new BigDecimal(s);
        Double d = bd.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        return d;
    }

    public Polygon DrawRectangular(List<LatLng> list) {
        PolygonOptions polygonOptions = new PolygonOptions();
        polygonOptions.addAll(list);
        polygonOptions.strokeWidth(15) // 多边形的边框
                .strokeColor(getResources().getColor(R.color.A1E0F2)) // 边框颜色
                .fillColor(Color.argb(1, 1, 1, 1));   // 多边形的填充色
        Polygon polygon = aMap.addPolygon(polygonOptions.zIndex(999));
        polygon.setZIndex(999);
        return polygon;
    }

    /**
     * 瓦片数据坐标转换
     */
    private String TileXYToQuadKey(int tileX, int tileY, int levelOfDetail) {
        StringBuilder quadKey = new StringBuilder();
        for (int i = levelOfDetail; i > 0; i--) {
            char digit = '0';
            int mask = 1 << (i - 1);
            if ((tileX & mask) != 0) {
                digit++;
            }
            if ((tileY & mask) != 0) {
                digit++;
                digit++;
            }
            quadKey.append(digit);
        }
        return quadKey.toString();
    }

    class MyAMapLocationListener implements AMapLocationListener {
        @Override
        public void onLocationChanged(final AMapLocation aMapLocation) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    location.setLatitude(aMapLocation.getLatitude());
                    location.setLongitude(aMapLocation.getLongitude());
                    location.setAddress(aMapLocation.getAddress());
                    location.setCountry(aMapLocation.getCountry());
                    location.setCity(aMapLocation.getCity());
                    location.setDistrict(aMapLocation.getDistrict());
                    location.setStreet(aMapLocation.getStreet());
                    location.setStreetNum(aMapLocation.getStreetNum());
                    location.setCityCode(aMapLocation.getCityCode());
                    location.setAdCode(aMapLocation.getAdCode());
                    location.setPoiName(aMapLocation.getPoiName());
                    location.setAoiName(aMapLocation.getAoiName());
                    location.setErrorCode(aMapLocation.getErrorCode());
                }
            };
            BHThreadPool.getInstance().executeTask(runnable);
        }
    }

    String userId = (String) SpUtils.get("module_user_id", "");

    public void addCode() {
        HTTPAPI.getInstance().addCode(userId, bean.getId() + "", new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("邀请码获取成功" + s);
                AddCodeCallBackBean bean = GsonUtil.GsonToBean(s, AddCodeCallBackBean.class);
                binding.tvModuleInviteCode.setText(bean.getResult().getCode() + "");
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("邀请码获取失败" + e.getMessage());
            }
        });
    }
}
